import pickle,base64
from django_redis import get_redis_connection

def merge_cart_cookie_to_redis(request,response,user):
    # 获取cookie值
    cart = request.COOKIES.get('cart')
    if not cart:
        return response
    # 对cookie值进行解密
    cart = pickle.loads(base64.b64decode(cart.encode()))
    cart_hash = {}
    selected_add = []
    selected_remove = []
    conn = get_redis_connection('cart')
    pl = conn.pipeline()
    # 把解密后的cookie值放入redis中
    for sku_id, count_selected_dict in cart.items():
        cart_hash[sku_id] = count_selected_dict['count']
        if count_selected_dict['selected']:
            selected_add.append(sku_id)
        else:
            selected_remove.append(sku_id)
            # conn.hset('cart_%s' % user.id, sku_id, count_dict['count'])
            # conn.sadd('cart_select_%s' % user.id, count_dict['selected'])

    pl.hmset('cart_%s' % user.id, cart_hash)
    if selected_add:
        pl.sadd('cart_select_%s' % user.id, *selected_add)
    if selected_remove:
        pl.srem('cart_select_%s' % user.id, *selected_remove)
    pl.execute()
    response.delete_cookie('cart')
    return response